/**
 * 岗位选择器
 */
import React from 'react';
import { Select, Spin } from 'antd';
import { useRequest } from '@/hooks';
import { connect } from 'umi';
import { fetchPost, fetchUsedPost } from '../../service';

function Post({ user, value, onChange, needFiltered, filterParams = {}, curDuty = [], ...props }) {
    const { companyId } = user;
    const { data: sourceData = [], loading } = useRequest(() => fetchPost({ organizationCode: companyId }), {
        formatResult: data => (Array.isArray(data.data) ? data.data : [])
    });
    const { data: filterData } = useRequest(() => fetchUsedPost(filterParams), {
        ready: !!needFiltered,
        formatResult: data => data?.data || []
    });

    const realData = React.useMemo(() => {
        if (!needFiltered) {
            return sourceData;
        }
        if (!filterData?.length || !sourceData?.length) {
            return curDuty;
        }
        return filterData.map(item => sourceData.find(s => s.dutyCode === item.dutyCode)).filter(item => !!item);
    }, [needFiltered, sourceData, filterData]);

    return (
        <Spin spinning={loading}>
            <Select
                style={{ width: 170 }}
                dropdownMatchSelectWidth={false}
                optionLabelProp="label"
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                allowClear
                getPopupContainer={triggerNode => triggerNode.parentElement}
                value={value}
                onChange={(_value, option) => {
                    onChange(_value, option);
                }}
                {...props}
            >
                {realData.map(item => (
                    <Select.Option value={item.dutyCode} key={item.dutyCode} options={item} label={item.dutyAlias}>
                        <span style={{ color: '#ccc' }}>{item.levelName}</span> {item.levelName ? '-' : ''}{' '}
                        {item.dutyAlias}
                    </Select.Option>
                ))}
            </Select>
        </Spin>
    );
}

export default connect(({ user }) => ({ user: user.currentUser }))(Post);
